<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>固定导航栏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            text-align: center;
        }

        img {
            vertical-align: top;
        }

        div.nav {
            position: fixed;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
        }

        #main {
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div id="top">
        <img src="./imgs/top.png" alt="">
    </div>
    <div id="nav">
        <img src="./imgs/nav.png" alt="">
    </div>
    <div id="main">
        <img src="./imgs/main.png" alt="">
    </div>
</body>
<script>
    window.onload = function () {
        var topDiv = document.querySelector('#top')
        console.log(topDiv);
        var navDiv = document.querySelector('#nav')
        var h = topDiv.offsetHeight
        console.log('h = ' + h);
        // 页面滚动的高度
        // console.log(window.pageYOffset);
        // 窗口滚动事件
        window.onscroll = function () {
            // console.log(window.pageYOffset);
            var scrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0
            if (scrollY >= h) {
                navDiv.className = 'nav'
            } else {
                navDiv.className = ''
            }
        }
    }

</script>

</html>